//go:build windows

/*
 * @Author: wangjun haodreams@163.com
 * @Date: 2025-01-02 23:21:57
 * @LastEditors: wangjun haodreams@163.com
 * @LastEditTime: 2025-01-02 23:22:47
 * @FilePath: \golib\ntp\ntpd\main_windows.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

package main

import (
	"log"
	"syscall"
	"time"
	"unsafe"
)

var (
	modkernel32       = syscall.NewLazyDLL("kernel32.dll")
	procSetSystemTime = modkernel32.NewProc("SetSystemTime")
)

type SYSTEMTIME struct {
	Year         uint16
	Month        uint16
	DayOfWeek    uint16
	Day          uint16
	Hour         uint16
	Minute       uint16
	Second       uint16
	Milliseconds uint16
}

func setSystemTimeWindows(year, month, day, hour, minute, second, milliseconds int) bool {
	var st SYSTEMTIME
	st.Year = uint16(year)
	st.Month = uint16(month)
	st.Day = uint16(day)
	st.Hour = uint16(hour)
	st.Minute = uint16(minute)
	st.Second = uint16(second)
	st.Milliseconds = uint16(milliseconds)
	ret, _, _ := procSetSystemTime.Call(uintptr(unsafe.Pointer(&st)))
	return ret != 0
}

func SetTime(now time.Time) (err error) {
	year, month, day := now.Date()
	hour, minute, second := now.Clock()
	milliseconds := int(now.Nanosecond() / 1000000)
	success := setSystemTimeWindows(year, int(month), day, hour, minute, second, milliseconds)
	if success {
		log.Println("Time set to:", now)
	} else {
		log.Println("Error setting time", now)
	}
	log.Println("now:", time.Now(), "\n")
	return
}
